package com.example.springtransdemo.controller;

import com.example.springtransdemo.service.LogService;
import com.example.springtransdemo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
    @RequestMapping("/user1")
    @RestController
    public class UserController1 {
        @Autowired
        private UserService userService;
        @Autowired
        private LogService logService;

        @Transactional
        @RequestMapping("/registry")
        public String registry(String name,String password){
            //开启事务

//⽤⼾注册
           int result= userService.registryUser(name,password);
log.info("用户注册成功，影响行数："+result);
//try {
//    int a=10/0;
//}catch (Exception e){
//log.error("用户注册失败");
//    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//throw new RuntimeException(e);
//}

            //提交事务
            return "注册成功";
        }

    @Transactional(rollbackFor = IOException.class)
    @RequestMapping("/r1")
    public String r1(String name,String password) throws IOException {
        //开启事务
//⽤⼾注册
        int result= userService.registryUser(name,password);

        if(true){
            throw new IOException();
        }
        log.info("用户注册成功，影响行数："+result);
        return "注册成功";
    }

    @Transactional()
    @RequestMapping("/r2")
    public String r2(String name,String password) throws IOException {
        //开启事务
//⽤⼾注册
        int result= userService.registryUser(name,password);

        if(true){
            throw new IOException();
        }
        log.info("用户注册成功，影响行数："+result);
        return "注册成功";
    }


    }

